# -*- coding: utf-8 -*-
import yaml, requests,json, pymysql,random,uuid
from datetime import datetime
from data_246 import *
from data_uat import *
from name import *
from log import *




def write_(path,data):
    with open(path,'w',encoding='utf-8')as file:
        yaml.dump(data=data,stream=file,allow_unicode=True)
        print('接口数据写入成功！')

def write_yaml(environment):
    yaml_path = uuid.uuid4().hex
    if environment=='154':
        write_(fr'D:\python\yaml\{yaml_path}.yaml', data1)
    if environment=='uat':
        write_(fr'D:\python\yaml\{yaml_path}.yaml', data_uat1)
    return yaml_path

def read_yaml(name,yaml_path):
    with open(fr'D:\python\yaml\{yaml_path}.yaml', 'r', encoding='utf-8') as file1:
        data = yaml.load(file1, Loader=yaml.FullLoader)
        return data[name]

def login():
    url = get_url('login')
    headers = get_headers('login')
    data =get_data('login')
    ree = send_requests( 'login', url, data, headers)
    a1 = json.loads(ree.text)
    token = a1['data']['token']
    return token

def send_requests(name,url,data,headers):
    if get_method(name)=='post':
        re = requests.post(url, data=json.dumps(data), headers=headers)
        return  re
    if get_method(name)=='get':
        re=requests.get(url, params=data,headers=headers)
        return  re

def unique(list1,list2):
    # 将列表转换为集合
    set1 = set(list1)
    set2 = set(list2)

    # 找出在list1中但不在list2中的元素
    unique_to_list1 = set1.difference(set2)
    # 找出在list2中但不在list1中的元素
    unique_to_list2 = set2.difference(set1)

    # 将结果转换回列表（如果需要）
    unique_to_list1_list = list(unique_to_list1)
    unique_to_list2_list = list(unique_to_list2)

    # 输出结果
    print("Elements unique to list1:", unique_to_list1_list)
    print("Elements unique to list2:", unique_to_list2_list)

def deal_list(original_list):
    # 新列表，用于存放分割后的去重元素
    unique_list = []
    # 遍历原始列表
    for item in original_list:
        # 检查元素是否为字符串并且包含逗号
        if isinstance(item, str) and ',' in item:
            # 直接打印出来机构
            print(item)
            # 分割字符串，并将分割后的元素添加到新列表中
            sub_list = item.split(',')
            # 去重，将分割后的列表转换为集合，再转回列表
            unique_list.extend(set(sub_list))
        else:
            # 如果不包含逗号，直接添加到新列表
            unique_list.append(item)

    # 去重后的新列表
    unique_list = list(set(unique_list))
    return unique_list
def process_approval(environment,flow_number):
    url = "http://172.16.91.154:5000/user-action?environment=%s&add_trans=3&flow_number=%s"%(environment,flow_number)
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    print(json.loads(response.text)['data'])

def upload_file(bizId,audit_id,auditNodeId,token_new,code):
    body_data=[]
    for c in range(1, 4):  # 一个审批人，多从上传附件
        # 获取当前日期和时间
        now = datetime.now()
        # 只获取当前日期
        today = now.date()
        # print(today)
        random_uuid = uuid.uuid4()
        # print("随机UUID:", random_uuid)
        # 上传附件到obs
        url = get_url('obsfile')
        headers = get_headers('obsfile')
        headers['Authorization'] = token_new
        expect = get_expect('obsfile')
        data = get_data('obsfile')
        file_type = ['pdf', 'jpg', 'png', 'docx', 'xls', 'xlsx']
        data['fileName'] = str(c) + '.' + random.choice(file_type)
        data['fileKey'] = '/employee/' + str(today) + '/' + str(random_uuid)
        # print(data)
        logger.info(data)
        ree = send_requests('obsfile', url=url, data=data, headers=headers)
        a = json.loads(ree.text)
        try:
            # 断言 'status' 的值是否等于 expect
            assert a['status'] == expect
            # print("上传附件到obs成功")
            logger.info("上传附件到obs成功")
            fileId = a['data']['fileId']
            fileName = a['data']['fileName']
            dic1 = {}
            if code==1:
                dic1['bizId'] = bizId
                dic1['auditId'] = audit_id
                dic1['auditNodeId'] = auditNodeId
                dic1['fileId'] = fileId
                dic1['fileName'] = fileName
                body_data.append(dic1)
                # print(body_data)
                logger.info(body_data)
            if code==2:
                dic1['fileId'] = fileId
                dic1['fileName'] = fileName
                body_data.append(dic1)
                # print(body_data)
                logger.info(body_data)
        except AssertionError:
            logger.info("断言失败：上传附件到obs失败")
            logger.error(a)
    return body_data


def get_url(name,yaml_path ):
    url=read_yaml(name,yaml_path)['url']
    return url
def get_headers(name,yaml_path):
    headers = read_yaml(name,yaml_path)['headers']
    return headers
def get_data(name,yaml_path):
    data=read_yaml(name,yaml_path)['data']
    return data

def get_expect(name,yaml_path):
    expect=read_yaml(name,yaml_path)['expect']
    return expect
def get_method(name,yaml_path):
    method=read_yaml(name,yaml_path)['method']
    return method




def mysql(base):

    #246数据库
    if base=='154':
        mysql_host = '172.16.91.155'
        mysql_port = 3306
        mysql_user = 'root'
        mysql_passwd = 'deke@2024'
        mysql_database = 'dekeinfo_154'
    if base=='uat':
    #UAT数据库
        mysql_host = 'test.derkee.com'
        mysql_port = 3306
        mysql_user = 'root'
        mysql_passwd = 'uat@dekeinf.mysql'
        mysql_database = 'uat'
    if base=='97':
    #UAT数据库
        mysql_host = '172.16.91.97'
        mysql_port = 3306
        mysql_user = 'root'
        mysql_passwd = 'dk'
        mysql_database = 'test'
    conn= pymysql.connect(host=mysql_host,port=mysql_port, user=mysql_user, passwd=mysql_passwd, charset='utf8', db=mysql_database)
    return conn

